package com.lee.dianjiqi;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.app.Instrumentation;
import android.content.Intent;
import android.graphics.Path;
import android.os.SystemClock;
import android.util.Log;
import android.view.MotionEvent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.lee.dianjiqi.utils.MyNotice;
import com.lee.dianjiqi.utils.ShellUtils;

import java.util.Random;

public class MyAccessibilityService extends AccessibilityService {

    private static final String TAG = "MyAccessibilityService";
    private AccessibilityNodeInfo rootWindow;

    /**
     * 设备链接后执行，可初始化
     */
    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();

        Log.d(TAG, "===========onServiceConnected===========");


    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.d(TAG, "===========onStartCommand===========");

        int x = intent.getIntExtra("x", 0);
        int y = intent.getIntExtra("y", 0);

        if (x == 0 && y == 0)
            return super.onStartCommand(intent, flags, startId);

//        slideScreen(x, y, x+1, y + 1);


        Random random = new Random();
        int r1 = random.nextInt(20) - 10;
        int r2 = random.nextInt(20) - 10;
        Log.d(TAG, "r1:" + r1 + ",r2:" + r2);

        myClickP(x + r1, y + r2);
//        click(x, y);

        MyNotice.getInstance().notifyMy("Click");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }


    /**
     * 当系统检测到与无障碍服务指定的事件过滤参数匹配的
     *
     * @param event
     */
    public synchronized void onAccessibilityEvent(AccessibilityEvent event) {
        //scroll();
//        Log.d(TAG, "=======onAccessibilityEvent===========");


    }


    private void refreshRootView() {
        rootWindow = getRootInActiveWindow();
    }

    /**
     * 当系统要中断服务正在提供的反馈（通常是为了响应将焦点移到其他控件等用户操作）时，会调用此方法。此方法可能会在服务的整个生命周期内被调用多次
     */
    public void onInterrupt() {

        Log.d(TAG, "===========onInterrupt===========");
    }


    @Override
    public boolean onUnbind(Intent intent) {

        Log.d(TAG, "===========onUnbind===========");

        return super.onUnbind(intent);
    }

    /**
     * 仿滑动
     */
    private void slideScreen(int x1, int y1, int x2, int y2) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            Path path = new Path();

            path.moveTo(x1, y1);//设置Path的起点
            path.lineTo(x2, y2);
            //path.quadTo(x1 + 10, y1, x2, y2);

            Log.d(TAG, "滑动x1:" + x1 + ",y1:" + y1 + ",x2:" + x2 + ",y2:" + y2);

            GestureDescription.Builder builder = new GestureDescription.Builder();
            GestureDescription description = builder.addStroke(new GestureDescription.StrokeDescription(path, 500L, 37L)).build();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //100L 第一个是开始的时间，第二个是持续时间
            dispatchGesture(description, null, null);
        } else {
            Log.d(TAG, "滑动x1:" + x1 + ",y1:" + y1 + ",x2:" + x2 + ",y2:" + y2);
            //input swipe 250 250 300 300 从屏幕(250, 250), 到屏幕(300, 300)即
            ShellUtils.adbShell("input swipe " + x1 + " " + y1 + " " + x2 + " " + y2);
        }
    }

    /**
     * 仿点击
     */
    private void myClickP(float x, float y) {
        Log.d(TAG, "点击的位置x:" + x + ",y:" + y);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            Path path = new Path();
            path.moveTo(x, y);//设置Path的起点
            path.lineTo(x, y);
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            GestureDescription.Builder builder = new GestureDescription.Builder();
            GestureDescription description = builder.addStroke(new GestureDescription.StrokeDescription(path, 5L, 5L)).build();
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //100L 第一个是开始的时间，第二个是持续时间
            dispatchGesture(description, null, null);
        } else {
            ShellUtils.adbShell("input tap " + x + " " + y);
        }
    }


    public void goBack() {
        performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
        refreshRootView();
    }


    private void click(int xx, int yy) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "xx:" + xx + ",yy:" + yy);
                Instrumentation mInst = new Instrumentation();
                mInst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),
                        SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, xx, yy, 0));    //x,y 即是事件的坐标
                mInst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),
                        SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, xx, yy, 0));
            }
        }).start();

    }

}
